package com.cqhz.quwan.ui.main.order

import android.content.Intent
import android.support.v4.view.PagerAdapter
import android.support.v4.view.ViewPager
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.cqhz.quwan.APP
import com.cqhz.quwan.ActivityInject
import com.cqhz.quwan.R
import com.cqhz.quwan.common.KeyContract
import com.cqhz.quwan.model.LoginBean
import com.cqhz.quwan.model.OrderBean
import com.cqhz.quwan.model.PageResultBean
import com.cqhz.quwan.mvp.mine.OrderListContract
import com.cqhz.quwan.mvp.mine.OrderListPresenter
import com.cqhz.quwan.ui.activity.OrderDetailActivity
import com.cqhz.quwan.ui.base.GoBackActivity
import com.cqhz.quwan.ui.login.LoginActivity
import com.cqhz.quwan.util.CommonAdapterHelper
import com.cqhz.quwan.util.CommonDecoration
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import kotlinx.android.synthetic.main.activity_order_list.*
import me.militch.quickcore.core.HasDaggerInject
import javax.inject.Inject

/**
 * 我的兑换
 * Created by Guojing on 2018/9/19.
 */
class OrderListActivity : GoBackActivity(), OrderListContract.View, HasDaggerInject<ActivityInject> {

    @Inject
    lateinit var orderListPresenter: OrderListPresenter
    private var loginBean: LoginBean? = null
    private var titles = arrayOf("全部订单", "待开奖订单", "中奖订单")
    private var pages = ArrayList<View>()
    private var holders = ArrayList<PageViewHolder>()
    private var adapters = ArrayList<BaseQuickAdapter<*, *>>()
    private var orders = ArrayList<ArrayList<OrderBean>>()

    override fun inject(t: ActivityInject?) {
        t?.inject(this)
    }

    override fun titleBarText(): String? {
        return "我的竞猜"
    }

    override fun layout(): Int {
        return R.layout.activity_order_list
    }

    override fun initView() {
        orderListPresenter.attachView(this)
        if (APP.get()!!.loginInfo != null) {
            loginBean = APP.get()!!.loginInfo
        }

        // 初始化页面元素和相应数据以及适配器
        for (i in 0 until titles.size) {
            initAdapter()
        }
        initPager()
        // 加载数据
        refreshCurrentPage()
    }

    /**
     * 初始化列表适配器
     */
    private fun initAdapter() {
        // 当前页面的布局
        var pageView = LayoutInflater.from(this).inflate(R.layout.layout_page, vp_content, false) as View
        var holder = PageViewHolder(pageView)

        // 当前页面列表的空布局
        var emptyView = LayoutInflater.from(this).inflate(R.layout.layout_none, holder.rvContent.parent as? ViewGroup, false) as View
        var ivNone = emptyView.findViewById(R.id.iv_none) as ImageView
        ivNone.setImageResource(0)

        // 当前页面列表的数据和适配器
        var orderList = ArrayList<OrderBean>()
        var orderListAdapter = CommonAdapterHelper.getOrderListAdapter(orderList)
        orderListAdapter.emptyView = emptyView

        // 当前页面列表适配器的事件
        holder.rvContent.layoutManager = LinearLayoutManager(this)
        holder.rvContent.addItemDecoration(CommonDecoration(1))
        holder.rvContent.adapter = orderListAdapter
        orderListAdapter.setOnLoadMoreListener({
            var currentPage = vp_content.currentItem
            if (orders[currentPage].size > 0) {
                if (orders[currentPage].size % KeyContract.pageSize == 0) {
                    var pageNo = orders[currentPage].size / KeyContract.pageSize + 1
                    holders[currentPage].refreshLayout.isEnableRefresh = false
                    orderListPresenter.getOrderList(loginBean!!.userId!!, currentPage, pageNo, KeyContract.pageSize)
                } else {
                    adapters[currentPage].loadMoreEnd()
                }
            } else {
                holders[currentPage].refreshLayout.isEnableRefresh = false
                orderListPresenter.getOrderList(loginBean!!.userId!!, currentPage, 1, KeyContract.pageSize)
            }
        }, holder.rvContent)
        holder.rvContent.addOnItemTouchListener(object : OnItemClickListener() {
            override fun onSimpleItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
                var currentPage = vp_content.currentItem
                val item = adapters[currentPage].getItem(position) as OrderBean

                val intent = Intent(context(), OrderDetailActivity::class.java)
                intent.putExtra(KeyContract.OrderId, item.id)
                startActivity(intent)
            }
        })
        // 刷新
        holder.refreshLayout.setOnRefreshListener { refreshCurrentPage() }

        // 将当前的页面、列表控件、数据列表、适配器加入相应的列表
        pages.add(pageView)
        holders.add(holder)
        orders.add(orderList)
        adapters.add(orderListAdapter)
    }

    /**
     * 初始化页面
     */
    private fun initPager() {
        vp_content.adapter = object : PagerAdapter() {
            override fun getCount(): Int {
                return pages.size
            }

            override fun isViewFromObject(view: View, `object`: Any): Boolean {
                return view === `object`
            }

            override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
                container.removeView(pages[position])
            }

            override fun instantiateItem(container: ViewGroup, position: Int): Any {
                var view = pages[position]
                var parent = view.parent as? ViewGroup
                parent?.removeAllViews()
                container.addView(view)
                return view
            }
        }
        st_tab.setViewPager(vp_content, titles)
        vp_content.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}

            override fun onPageSelected(position: Int) {
                if (orders[position].size <= 0) {
                    refreshCurrentPage()
                }
            }

            override fun onPageScrollStateChanged(state: Int) {}
        })
    }

    /**
     * 刷新当前页面
     */
    private fun refreshCurrentPage() {
        if (loginBean != null) {
            var currentPage = vp_content.currentItem
            orderListPresenter.getOrderList(loginBean!!.userId!!, currentPage, 1, KeyContract.pageSize)
        } else {
            startActivity(Intent(this, LoginActivity::class.java))
        }
    }

    override fun loadOrderList(currentPage: Int, pageNo: Int, pageResultBean: PageResultBean<OrderBean>) {
        if (pageNo == 1) {
            orders[currentPage].clear()
            adapters[currentPage].setEnableLoadMore(true)
            if (holders[currentPage].refreshLayout.state.isHeader!!) {
                holders[currentPage].refreshLayout.finishRefresh()
            }
        }

        if (pageResultBean.records.isNotEmpty()) {
            orders[currentPage].addAll(pageResultBean.records)
        }

        if (pageResultBean.total > orders[currentPage].size) {
            adapters[currentPage].loadMoreComplete()
        } else {
            adapters[currentPage].loadMoreEnd()
        }

        adapters[currentPage].notifyDataSetChanged()
        holders[currentPage].refreshLayout.isEnableRefresh = true
    }

    internal class PageViewHolder(view: View) {
        var rvContent = view.findViewById(R.id.rv_content) as RecyclerView
        var refreshLayout = view.findViewById(R.id.refreshLayout) as SmartRefreshLayout
    }

    override fun onDestroy() {
        super.onDestroy()
        orderListPresenter.detachView()
    }
}
